const net = require('net');

// 用户对象
let clients = {};

const server = net.createServer(socket => {
    let userName;
    socket.setEncoding('utf8');
    server.getConnections((err,count) => {
        socket.write('欢迎进入tcp聊天室，当前有'+ count +'个人，请输入你的昵称\r\n');
    })
    socket.on('data', data => {
        data = data.replace(/\r\n/,'');
        if(userName) {
            broadcast(userName,`${userName}:${data}`);
        }else {
            if(clients[data]) {
                socket.write('用户名已经被占用，请重新输入昵称\r\n');
            }else {
                userName = data;
                clients[userName] = socket;
                broadcast(userName,`欢迎${userName}来到聊天室`);
            }
        }
    });
    socket.on('end', () => {
        broadcast(userName,`欢送${userName}离开聊天室`);
        clients[userName] && clients[userName].destroy(); // 销毁此cocket
        delete clients[userName];
    });
});

const broadcast = (name,msg) => {
    for(let n in clients) {
        if(n != name) {
            clients[n].write(msg + '\r\n');
        }
    }
}

server.listen(8081, () => {
    console.log('tcp聊天室启动成功，信息是：',server.address());
});